package it.polimi.swKnights.SWIMv2.filters;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerRemote;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Admin;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Founder;
import it.polimi.swKnights.SWIMv2.general.Errors;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AdminOnlyFilter
 */
public class AdminOnlyFilter extends SwimFilter implements Filter
{
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{

		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		String username = (String) session.getAttribute("userName");

		this.loginBean = this.lookUp(LoginHandlerRemote.class);

		if (loginBean.hasPrivileges(username, Admin.class))
		{
			request.setAttribute("isFounder", this.isFounder(username));
			chain.doFilter(request, response);

		}
		else
		{
			HttpServletResponse resp = (HttpServletResponse) response;
			this.setupSessionType(session, "admin", "logged");
			resp.sendRedirect("./userHome?error="+ Errors.notadmin);
		}
		
		this.loginBean = null;

	}

	private boolean isFounder(String userName)
	{
		if (this.loginBean.hasPrivileges(userName, Founder.class))
			return true;
		else
			return false;
	}

	private LoginHandlerRemote loginBean;

}
